var canvas;
var ctx;
var width, height;
var dartBackground = "#007226";
var colorMaster1 = "#e34c37";
var colorMaster2 = "#007e56";
var colorNormal1 = "#f3e4c5";
var colorNormal2 = "#010101";
var colorGrid = "#999999";

var gameID = null;

var countArray  = [6,10,15,2,17,3,19,7,16,8,11,14,9,12,5,20,1,18,4,13];

var radOuter, radDouble, radTripleOuter, radTripleInner, radBull, radDoubleBull = 0;

var dartScoreBoardWin = null;

// Converts from degrees to radians.
Math.radians = function(degrees) {
    return degrees * Math.PI / 180;
};

Math.degrees = function(radians) {
    return radians * (180)/Math.PI;
};

function init() {
	canvas = document.getElementById('dartcanvas');
	if(canvas!=null) {
		ctx = canvas.getContext("2d");

		width = jQuery(canvas).width();
		height = jQuery(canvas).height();

		clear();
		generateDartGrid();
		drawNumbers();
		generateOverlay();
	}

	gameID = jQuery(canvas).data("game-id");
	gameUUID = jQuery(canvas).data("game-uuid");
	manr = jQuery(canvas).data("manr");

	jQuery.initWindowMsg();
	var url = "dartautomat.php?request=startdartscoreboard";
	var params = window.location.href.slice(window.location.href.indexOf('&') + 1);
	url = url + "&" + params;
	url = url + "&game_id=" + gameID;
	dartScoreBoardWin = window.open(url,"Scoreboard", "width=1300, height=800, location=no, menubar=no, scrollbars=no, status=no, toolbar=no");

	jQuery('#undo').click(function() {
		var form = $(this);
		var formData = $(this).serializeArray();
		$.ajax({
			type: form.attr('method'),
			url: form.attr('action'),
			data: formData
		}).done(function(data) {
			jQuery.triggerWindowEvent(dartScoreBoardWin, "dartboardMsg", JSON.stringify(formData));
			$('.regular:last').removeClass('regular').addClass('undo');
		});
		event.preventDefault(); // Prevent the form from submitting via the browser.
	});
}

function initMousePointer() {
	if(canvas) {
		canvas.addEventListener('mouseup', mouseClick, true);
	}
}

function mouseClick(e) {

	jQuery(canvas).css("border","5px solid red");

	var pX, pY;
	pX = e.pageX - canvas.offsetLeft;
	pY = e.pageY - canvas.offsetTop;
	center = canvas.width/2;
	distanceX = Math.abs(center - pX);
	distanceY = Math.abs(center - pY);

	centerP = {'x': center, 'y': center};
	hitP = {'x':pX, 'y':pY};
	offP = {'x': 0, 'y': radius};

	angle = Math.degrees(getAngle(offP, hitP, centerP));
	angle = angle - 180;
	if(center < pY) {
		angle = Math.abs(angle);
	} else {
		angle = 360 + angle;
	}

	distanceC = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

	result = getDartValue(angle, distanceValue(distanceC));
	console.log(result);

	paintHit(pX,pY);

	writeToValues(result);
}

function paintHit(x,y) {
	 var radius = 3;
	 var circ = Math.PI * 2;
	 var quart = Math.PI / 2;
	 var context = $(canvas)[0].getContext('2d');
     context.beginPath();
     context.arc(x-4, y-4, radius, - quart, circ - quart, false);
     context.stroke();
 }

function writeForDrops(value) {
	players = getPlayersFromURLParameters();
	data = {};
	data.request = 'spreadDropouts';
	data.game_id = $(value).data('gameid');
	data.manr = $(value).data('manr');
	data.players = $(value).data('playerid');
	data.playerid = players;

	$.ajax({
		url: "dartautomat.php",
		type: "GET",
		data: data,
		success: function(response) {
			jQuery("#dartscoreboard").html(response);
		}
	});
}
function writeToValues(value) {
	data = {};

	//split value to write
	score = value.split('_')[0];
	score_multiplier = value.split('_')[1];

	var players = new Array();
	players = getPlayersFromURLParameters();

	if(score && score_multiplier) {
		data.request = 'dartboard';
		data.game_id = gameID;
                data.manr = manr;
		data.game_uuid = gameUUID;
		data.score = score;
		data.score_multiplier = score_multiplier;
		data.playerid = players;

		jQuery.triggerWindowEvent(dartScoreBoardWin, "dartboardMsg", JSON.stringify(data));
	}
	if (score_multiplier > 1) {
		scoreString = score_multiplier +"x"+score;
	} else{
		var scoreString = score;
	}
	if (jQuery('#scores').html() == ""){
		jQuery('#scores').html(jQuery('#scores').html()+'<span class="regular">'+scoreString+"</span>");
	} else {
		jQuery('#scores').html(jQuery('#scores').html()+'> <span class="regular">'+scoreString+"</span>");
	}
	setTimeout( function(){
		$(canvas).css("border","5px solid black");
    },800);
}

function getPlayersFromURLParameters(){

	var url = window.location.href;
    var result = new Array();
    var searchIndex = url.indexOf("?");
    if (searchIndex == -1 ) return result;
    var sPageURL = url.substring(searchIndex +1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
		if (sParameterName[0] == 'playerid%5B%5D') {
			result.push(sParameterName[1]);
		}
    }
    return result;
}

function loadGameResult(result) {
	jQuery("#dartscoreboard").html(result);
}

function getDartValue(angle, multiplier ) {
	var i = 0;
	for(i = 0; i < countArray.length; i++) {

	}
	switch(multiplier) {
		case 50:
			return '25_2';
		case 25:
			return '25_1';
		case 3:
			return getNumberForAngle(angle) + '_3';
		case 2:
			return getNumberForAngle(angle) + '_2';
		case 1:
			return getNumberForAngle(angle) + '_1';
		case 0:
			return '0_0';
	}
}

function getNumberForAngle(angle) {
	var retValue = '';
	var i = 0;

	calcAngle = angle + 9;
	if(calcAngle > 360) {
		calcAngle = calcAngle - 360;
	}

	for(i=1;i<21;i++) {
		if (calcAngle < i*18) {
			return countArray[i-1];
		}
	}

	return retValue;
}

function distanceValue(distance) {
	if( distance < radDoubleBull) {
		return 50;
	} else if(distance > radDoubleBull && distance < radBull) {
		return 25;
	} else if(distance > radBull && distance < radTripleInner) {
		return 1;
	} else if(distance > radTripleInner && distance < radTripleOuter) {
		return 3;
	} else if(distance > radTripleOuter && distance < radDouble) {
		return 1;
	} else if(distance > radDouble && distance < radOuter) {
		return 2;
	} else {
		return 0;
	}
}

function getAngle(p1,p2,center) {
    var p1c = Math.sqrt(Math.pow(center.x-p1.x,2)+
                        Math.pow(center.y-p1.y,2)); // p1->c (b)
    var p2c = Math.sqrt(Math.pow(center.x-p2.x,2)+
                        Math.pow(center.y-p2.y,2)); // p2->c (a)
    var p1p2 = Math.sqrt(Math.pow(p2.x-p1.x,2)+
                         Math.pow(p2.y-p1.y,2)); // p1->p2 (c)
    return Math.acos((p2c*p2c+p1c*p1c-p1p2*p1p2)/(2*p2c*p1c));
}

function clear() {
	canvas.width = width;
	canvas.height = height;
	
    if(canvas.width < canvas.height) {
        canvas.height = canvas.width;
    } else {
        canvas.width = canvas.height;
    }
    
    ctx.save();
    ctx.fillStyle = dartBackground;
    ctx.fillRect(0,0,width,height);
    ctx.restore();
}

function generateDartGrid() {
    radius = canvas.width/2;
    center = [radius,radius];
	//console.log('center:' + center)

	radOuter = radius - radius/10;
	radDouble = radOuter - radius/12;
	radTripleOuter = radOuter - (radOuter*0.37);
	radTripleInner = radTripleOuter - radOuter/12;
	radBull = radOuter-radOuter*0.9;
	radDoubleBull = radOuter-radOuter*0.96;

	drawCircle(radius, "#000000");
	drawGrid(radOuter, true, colorMaster1, colorMaster2);
	drawGrid(radDouble, false, colorNormal1, colorNormal2);
	drawGrid(radTripleOuter, true, colorMaster1, colorMaster2);
	drawGrid(radTripleInner, false, colorNormal1, colorNormal2);
	drawCircle(radBull, colorMaster2);
	drawCircle(radDoubleBull, colorMaster1);

	//console.log(radOuter, radTripleOuter, radTripleInner, radBull, radDoubleBull);
}

function generateOverlay() {
	ol = jQuery('.dartomat .overlay')[0];
	jQuery(ol).css('width', canvas.width).css('height', canvas.height).css('line-height', canvas.height+'px');	
}

function drawGrid(radius, even, color1, color2) {
    grid = 360 / 20;
    startAngle = 0 + grid / 2;
    while(startAngle<369) {

        toAngle = startAngle + grid;
        ctx.beginPath();
        ctx.arc(center[0], center[0], radius, Math.radians(startAngle), Math.radians(toAngle), false);
		ctx.lineTo(center[0], center[0]);
		ctx.closePath();
		ctx.lineWidth = 1;
		ctx.strokeStyle = colorGrid;
        if(even) {
            ctx.fillStyle = color1;
        } else {
            ctx.fillStyle = color2;
        }
        ctx.fill();
		ctx.stroke();

        startAngle = toAngle;
        even = !even;
    }
}

function drawCircle(radius, color) {
	ctx.beginPath();
	ctx.arc(center[0], center[0], radius, Math.radians(0), Math.radians(360), false);
	ctx.closePath();
	ctx.lineWidth = 2;
	ctx.strokeStyle = colorGrid;
	ctx.fillStyle = color;
	ctx.fill();
	ctx.stroke();
}

function drawNumbers() {
	var fontHeight = radius - radOuter - 10;
	ctx.beginPath();
	ctx.fillStyle = "white";
	ctx.font = "bold "+ fontHeight + "px Arial";

	var digitCount = 20;
	var digitRad = radOuter + fontHeight/2 + 5;

	for (var i = 0; i < digitCount; ++i) {
	  ctx.beginPath();
	  var angle = i*2*Math.PI/digitCount;
	  var x = center[0] + Math.cos(angle) * digitRad;
	  var y = center[0] + Math.sin(angle) * digitRad;
	  ctx.textAlign = "center";
	  ctx.fillText(countArray[i], x, y+10, 50);
	  ctx.fillStyle = "white";
	  ctx.fill();
	}
}